"use client";

import { useState } from "react";
import {
  ResizablePanel,
  ResizablePanelGroup,
  ResizableHandle,
} from "@/components/ui/resizable";
import { Sidebar } from "@/components/sidebar";
import { DocumentView } from "@/components/document-view";
import { UserRole } from "@/types/auth";
import MarkdownEditor from "@/components/markdown-editor";
import MarkdownPreview from "@/components/markdown-preview";

export function KnowledgeBase() {
  const [selectedDocId, setSelectedDocId] = useState<string | null>(null);
  // 模拟当前用户角色，实际应用中应从认证系统获取
  const userRole: UserRole = "admin"; // 可以是 "superAdmin" | "admin" | "employee"
  const [documentContent, setDocumentContent] = useState<string>("");
  const [isEditing, setIsEditing] = useState<boolean>(false);

  // 检查用户是否有编辑权限
  const canEdit = userRole === "superAdmin" || userRole === "admin";

  // 当选择文档变化时获取文档内容
  const handleDocumentSelect = (docId: string | null) => {
    setSelectedDocId(docId);
    setIsEditing(false);
    if (docId) {
      // 这里可以从API获取文档内容，现在使用模拟数据
      const content = getInitialContent(docId);
      setDocumentContent(content);
    } else {
      setDocumentContent("");
    }
  };

  // 切换编辑模式
  const toggleEditMode = () => {
    if (canEdit && selectedDocId) {
      setIsEditing(!isEditing);
    }
  };

  return (
    <div className='flex h-screen overflow-hidden'>
      <ResizablePanelGroup direction='horizontal'>
        <ResizablePanel defaultSize={18} minSize={15} maxSize={40}>
          <Sidebar
            onSelectDocument={handleDocumentSelect}
            selectedDocId={selectedDocId}
            userRole={userRole}
          />
        </ResizablePanel>
        <ResizableHandle withHandle />
        {isEditing && selectedDocId ? (
          <>
            <ResizablePanel defaultSize={41}>
              <div className='flex flex-col h-full'>
                <div className='p-4 border-b flex justify-between items-center'>
                  <h2 className='text-lg font-medium'>编辑区域</h2>
                  <button
                    onClick={toggleEditMode}
                    className='px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600'
                  >
                    切换到查看模式
                  </button>
                </div>
                <div className='flex-1 overflow-auto p-4'>
                  <MarkdownEditor
                    initialContent={documentContent}
                    onSave={(content) => console.log("保存内容:", content)}
                    onChange={setDocumentContent}
                  />
                </div>
              </div>
            </ResizablePanel>
            <ResizableHandle withHandle />
            <ResizablePanel defaultSize={41}>
              <div className='flex flex-col h-full'>
                <div className='p-4 border-b'>
                  <h2 className='text-lg font-medium'>预览区域</h2>
                </div>
                <div className='flex-1 overflow-auto p-4'>
                  <MarkdownPreview content={documentContent} isHtml={true} />
                </div>
              </div>
            </ResizablePanel>
          </>
        ) : (
          <ResizablePanel defaultSize={82}>
            <div className='flex flex-col h-full'>
              <div className='p-4 border-b flex justify-between items-center'>
                <h2 className='text-lg font-medium'>
                  {selectedDocId
                    ? getDocumentTitle(selectedDocId)
                    : "请选择文档"}
                </h2>
                {canEdit && selectedDocId && (
                  <button
                    onClick={toggleEditMode}
                    className='px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600'
                  >
                    编辑文档
                  </button>
                )}
              </div>
              <div className='flex-1 overflow-auto'>
                <DocumentView
                  documentId={selectedDocId}
                  content={documentContent}
                  userRole={userRole}
                />
              </div>
            </div>
          </ResizablePanel>
        )}
      </ResizablePanelGroup>
    </div>
  );
}

// 辅助函数，获取初始文档内容
function getInitialContent(docId: string): string {
  // 这里可以从API获取文档内容，现在使用模拟数据
  return `# ${getDocumentTitle(docId)}

这是一个示例文档内容。

## 章节一

这里是一些示例内容，可以包含**粗体**、*斜体*等Markdown格式。

- 列表项1
- 列表项2
- 列表项3

## 章节二

这里是更多的内容...

\`\`\`javascript
// 示例代码
function example() {
  console.log("Hello, World!");
}
\`\`\`
`;
}

// 辅助函数，根据ID获取文档标题
function getDocumentTitle(id: string): string {
  const titles: Record<string, string> = {
    "1-1": "产品规划",
    "1-2": "用户手册",
    "1-3-1": "架构设计",
    "1-3-2": "API文档",
    "2-1": "员工手册",
    "2-2": "休假制度",
  };

  return titles[id] || "未知文档";
}
